import { insertCart, findCartList, deleteCart, updateCart, checkAllCart } from '@/api/cart'
import { setData, getData } from '@/utils/ls'
const RABBITCART = 'rabbit-cart'
export default {
  namespaced: true,
  state: {
    cartList: getData(RABBITCART) || []
  },
  getters: {
    // cartList中每一项的count字段值累加之和 reduce
    allCount (state) {
      return state.cartList.reduce((a, c) => a + c.count, 0)
    },
    // cartList中每一项的count * price累加之和 reduce
    allPrice (state) {
      return state.cartList.reduce((a, c) => a + c.count * c.price, 0)
    },
    // 已选择商品 selected true的就是被选中的 过滤出来所有selected字段为true的项
    selectedCount (state) {
      return state.cartList.filter(item => item.selected).reduce((a, c) => a + c.count, 0)
    },
    selectedPrice (state) {
      return state.cartList.filter(item => item.selected).reduce((a, c) => a + c.count * c.price, 0)
    },
    isAll (state) {
      // 数组中所有项的selected都为true
      // every some
      return state.cartList.every(item => item.selected)
    }
  },
  mutations: {
    setCartList (state, list) {
      state.cartList = list
      setData(RABBITCART, list)
    },
    singleCheck (state, { skuId, selected }) {
      // 通过skuId找到要修改的那一项  find findIndex
      const item = state.cartList.find(item => item.skuId === skuId)
      // 把找到项的selected字段改成传入的单选项最新的状态
      item.selected = selected
      // 更新本地ls
      setData(RABBITCART, state.cartList)
    }
  },
  actions: {
    // 加入购物车
    async insertCart (ctx, { skuId, count }) {
      // 1. 添加购物车的接口
      await insertCart({ skuId, count })
      // 2. 调用一个获取购物车列表的接口
      const res = await findCartList()
      // 3. 提交mutation函数把购物车列表存入state[ls]
      ctx.commit('setCartList', res.result)
    },
    // 删除购物车
    async delCart (ctx, ids) {
      // 1. 删除接口
      await deleteCart(ids)
      // 2. 调用一个获取购物车列表的接口
      const res = await findCartList()
      // 3. 提交mutation函数把购物车列表存入state[ls]
      ctx.commit('setCartList', res.result)
    },
    // 单选购物车
    async singleCheck (ctx, goods) {
      // 1. 调用单选接口
      await updateCart(goods)
      // 2. 调用一个获取购物车列表的接口
      const res = await findCartList()
      // 3. 提交mutation函数把购物车列表存入state[ls]
      ctx.commit('setCartList', res.result)
    },
    // 全选功能
    async allCheck (ctx, selected) {
      // 1. 调用全选接口
      await checkAllCart({
        selected,
        ids: ctx.state.cartList.map(item => item.skuId)
      })
      // 2. 调用一个获取购物车列表的接口
      const res = await findCartList()
      // 3. 提交mutation函数把购物车列表存入state[ls]
      ctx.commit('setCartList', res.result)
    }
  }
}
